package com.cyq.dascma.interceptor;

import com.cyq.dascma.result.ResultGenerator;
import com.cyq.dascma.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * dingwen
 * 2021/4/3 21:36
 **/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入登录拦截器 {}", DateTimeUtil.getSystemTime());
        // 接口文档放行
        try {
            if (((HandlerMethod) handler).getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")) {
                return true;
            }
        } catch (Exception e) {
            return true;
        }
        //todo cookie 解决
        if (judgeCookie(request)|| true) {
            return true;
        } else {
            log.info("未登录，即将跳转登录页 {}", DateTimeUtil.getSystemTime());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().print(ResultGenerator.genFailureResult("未登录").setCode(401));
            return false;
        }

    }

    /**
     * 从request 中取出 cookie
     */
    private boolean judgeCookie(HttpServletRequest request) {
        try {
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                return false;
            }
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    return true;
                }
            }
        } catch (Throwable e) {
            return false;
        }
        return false;
    }
}
